﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using API.Models;
using PPG.DataAccess;
using PPG.CryptoProvider;
using System.Xml;
using System.Data;
using System.Configuration;
using System.Web;

namespace API.Controllers
{
    public class UserForgotPasswordController : ApiController
    {
        /// <summary>
        /// Intializing Helper Classes - DB Connection and Security Provider for Encrypting and Decrypting Passwords
        /// Pass in DBServerName, DBUsern
        /// ame and DBPassword from Config File for DB connections
        /// The Security helper does nto take any parameters
        /// </summary>
        DataSourceCommunicator dsComm = new DataSourceCommunicator(DataSourceCommunicator.ParamType.ServerCredentials, ConfigurationManager.AppSettings["DBServerName"].ToString(), ConfigurationManager.AppSettings["DBUserName"].ToString(), ConfigurationManager.AppSettings["DBPassword"].ToString());

        [ActionName("UserForgotPassword")]
        public UserForgotPasswordResponse PostUserForgotPassword([FromBody]UserForgotPasswordRequest request)
        {

            UserForgotPasswordResponse response = new UserForgotPasswordResponse();
            if (!String.IsNullOrEmpty(request.UserName) && String.IsNullOrEmpty(request.NewPassword))
            {
                dsComm.AddParameter("@ParamUsername", request.UserName);
                string data = dsComm.ExecuteStoredProcedure("dbo.spGetUserPwdDetailsByUsername");
                XmlTextReader xReader = new XmlTextReader(data, XmlNodeType.Document, null);
                DataSet UserDataSet = new DataSet();
                UserDataSet.ReadXml(xReader);

                if (UserDataSet.Tables.Count > 0)
                {
                    if (UserDataSet.Tables[0].Rows.Count > 0)
                    {
                        response.SecretQuestion = UserDataSet.Tables[0].Rows[0][0].ToString();
                    }
                    else
                    {
                        response.ErrorMsg = "User Not Found";
                    }
                }
                else
                {
                    response.ErrorMsg = "User Not Found";
                }
            }
            else if(!String.IsNullOrEmpty(request.UserName) && !String.IsNullOrEmpty(request.NewPassword))
            {
                dsComm.AddParameter("@ParamUsername", request.UserName);
                string data = dsComm.ExecuteStoredProcedure("dbo.spGetUserPwdDetailsByUsername");
                XmlTextReader xReader = new XmlTextReader(data, XmlNodeType.Document, null);
                DataSet UserDataSet = new DataSet();
                UserDataSet.ReadXml(xReader);
                CryptoAgent securityHandler = new CryptoAgent();

                if (UserDataSet.Tables.Count > 0)
                {
                    if (UserDataSet.Tables[0].Rows.Count > 0)
                    {
                        string SecretAns = securityHandler.decryptText(UserDataSet.Tables[0].Rows[0][1].ToString());
                        if (SecretAns.ToLower().Equals(request.SecretAnswer.ToLower()))
                        {
                            dsComm.AddParameter("@ParamUsername", request.UserName);
                            dsComm.AddParameter("@ParamPassword", securityHandler.EncryptText(request.NewPassword));
                            int datapwd = dsComm.ExecuteNonQuery("dbo.spPostNewPwdByUsername");
                            if (datapwd > 0)
                            {
                                response.ErrorMsg = "Password Updated";
                            }

                        }
                        else
                        {
                            response.ErrorMsg = "Secret Answer didnt Match";
                        }
                    }
                    else
                    {
                        response.ErrorMsg = "User Not Found";
                    }
                   
                }
                else
                {
                    response.ErrorMsg = "User Not Found";
                }

            }
            return response;

        }
        /// <summary>
        /// Options Resposen for the preflight request of a CORS Opertaions. Will be standard across various functions
        /// </summary>
        /// <returns></returns>
        public HttpResponseMessage OptionsValidateUserLogin()
        {
            var response = new HttpResponseMessage();
            response.StatusCode = HttpStatusCode.OK;
            return response;
        }
    }
}
